<template>
  <div class="login_page col-center">
    <div v-if="!errorMsg" class="col-center">
      <van-loading type="spinner" color="#0094ff" />
      <span class="mt10">登录中...</span>
    </div>
    <template v-else>
      <p>登录失败!</p>
      <p>{{ errorMsg }}</p>
    </template>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue'
  import { useUserStore } from '@/store'
  import { useRoute } from 'vue-router'
  import { API } from '@/api'
  import router from '@/router'
  import { Loading } from 'vant'
  import { isDev } from '@/util'
  import { User } from '@/type'

  const getRedirectParams = (query: any) => {
    const { redirectTo, ...otherParams } = query

    return {
      redirectTo,
      otherParams
    }
  }

  export default defineComponent({
    name: 'Login',
    components: {
      [Loading.name]: Loading
    },
    setup() {
      const errorMsg = ref('')

      const route = useRoute()

      const store = useUserStore()

      const params = route.query

      const redirect = getRedirectParams(params)

      const dev = isDev()

      console.log('---isDev---', dev)
      console.log('-----getMyParams-----', params)
      console.log('---redirect---', redirect)

      const loginComplete = (user: User) => {
        // 完成登录，然后跳转
        // 此页面中的 redirect 信息参数是在路由拦截中加上的，
        // 具体代码在 RouterConfig 中

        store.login(user)

        if (redirect.redirectTo) {
          router.replace({
            path: redirect.redirectTo,
            query: redirect.otherParams
          })
        } else {
          console.log('--home--')
          router.replace({
            path: '/home'
          })
        }
      }

      const login = () => {
        if (!dev) {
          if (params.sessionid) {
            API.login({
              sessionId: params.sessionid
            }).then((res) => {
              if (res.success) {
                if (res.data.userid) {
                  loginComplete(res.data)
                } else {
                  errorMsg.value = '登陆失败，userid为空'
                }
              } else {
                errorMsg.value = JSON.stringify(res)
              }
            })
          }
        } else {
          const testUser = {
            userid: '20008225',
            wxToken: 'e533d68c7fe12417fd4c0ab9a33f65e9',
            wxOpenid: 'otKsjxP2llfgLrGLUEcnrbh7Bvzs',
            phone: '13210635346'
          }
          loginComplete(testUser)
        }
      }

      login()

      return {
        errorMsg
      }
    }
  })
</script>
<style>
  .login_page {
    height: 100%;
    font-size: 16px;
    padding: 50px 16px;
  }
</style>
